# -*- coding: utf-8 -*-

from PyQt4 import Qt, QtGui, QtCore

from Ui_MainWindow import Ui_MainWindow
from MdiWindow import MdiWindow
from FeAbout import FeAbout
from FeOptions import FeOptions


# Класс основного окна.
# Окно просто перенаправляет запросы на сохранение, загрузку, копирование и т.д. активному окну (типа MdiChild).
# Какие-то запросы, разумеется, обрабатывает само.

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.workspace = QtGui.QWorkspace(self)
        self.setCentralWidget(self.workspace)

        self.statusLabel = QtGui.QLabel(self)
        self.statusBar().addWidget(self.statusLabel)


        self.connect(self.ui.actionNew, QtCore.SIGNAL('triggered()'), self.new)
        self.connect(self.ui.actionOpen, QtCore.SIGNAL('triggered()'), self.open_)
        self.connect(self.ui.actionSave, QtCore.SIGNAL('triggered()'), self.save)
        self.connect(self.ui.actionSaveAs, QtCore.SIGNAL('triggered()'), self.saveAs)
        self.connect(self.ui.actionExportPdf, QtCore.SIGNAL('triggered()'), self.exportPdf)
        self.connect(self.ui.actionClose, QtCore.SIGNAL('triggered()'), self.workspace, QtCore.SLOT('closeActiveWindow()'))
        self.connect(self.ui.actionCloseAll, QtCore.SIGNAL('triggered()'), self.workspace, QtCore.SLOT('closeAllWindows()'))
        self.connect(self.ui.actionExit, QtCore.SIGNAL('triggered()'), QtGui.qApp, QtCore.SLOT('quit()'))


        self.connect(self.ui.actionCut, QtCore.SIGNAL('triggered()'), self.cut)
        self.connect(self.ui.actionCopy, QtCore.SIGNAL('triggered()'), self.copy)
        self.connect(self.ui.actionPaste, QtCore.SIGNAL('triggered()'), self.paste)
        self.connect(self.ui.actionDelete, QtCore.SIGNAL('triggered()'), self.delete)
        self.connect(self.ui.actionSelectAll, QtCore.SIGNAL('triggered()'), self.selectAll)
        self.connect(self.ui.actionOptions, QtCore.SIGNAL('triggered()'), self.options)

        self.connect(self.ui.actionAbout, QtCore.SIGNAL('triggered()'), self.about)

        self.connect(self.workspace, QtCore.SIGNAL('windowActivated(QWidget*)'), self.setActionsEnabled)
        self.connect(QtGui.QApplication.clipboard(), QtCore.SIGNAL('dataChanged()'), self.onClipboardDataChanged)

        self.nextWindowIndex = 1
        self.setActionsEnabled()




    def getSaveFileName(self, ext, extUser):
        fileDialog = QtGui.QFileDialog(self, Qt.Qt.Dialog)
        fileDialog.setNameFilter(extUser)
        fileDialog.setDefaultSuffix(ext)

        fileDialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
        if not fileDialog.exec_():
            return None

        filelist = fileDialog.selectedFiles()
        if filelist.count() == 0:
            return None

        return unicode(filelist[0])


    def getMdiWindow(self):
        mdiWindow = MdiWindow(self)
        self.connect(mdiWindow, QtCore.SIGNAL('stateChanged(QWidget*)'), self.setActionsEnabled)
        self.workspace.addWindow(mdiWindow)
        return mdiWindow



    def new(self):
        mdiWindow = self.getMdiWindow()
        mdiWindow.setWindowTitle(u"Коллекция %d" % self.nextWindowIndex)
        mdiWindow.show()
        self.setActionsEnabled()
        self.nextWindowIndex += 1

    def save(self):
        filename = self.workspace.activeWindow().filename()
        if filename is None:
            filename = self.getSaveFileName(MainWindow.extMcf, MainWindow.extMcfUser)
            if filename is None:
                return
        self.workspace.activeWindow().save(filename)
        self.setActionsEnabled()

    def saveAs(self):
        filename = self.getSaveFileName(MainWindow.extMcf, MainWindow.extMcfUser)
        if filename is None:
            return
        self.workspace.activeWindow().save(filename)
        self.setActionsEnabled()
        

    def open_(self):
        filename = QtGui.QFileDialog.getOpenFileName(self, u"Открыть коллекцию фильмов", "", MainWindow.extMcfUser)
        if filename.length() == 0:
            return
        filename = unicode(filename)

        for mdiWindow in self.workspace.windowList():
            if mdiWindow.filename() == filename:
                self.workspace.setActiveWindow(mdiWindow)
                return

        mdiWindow = self.getMdiWindow()
        mdiWindow.load(filename)
        mdiWindow.show()
        self.setActionsEnabled()

    def cut(self):
        self.workspace.activeWindow().cut()
        self.setActionsEnabled()

    def copy(self):
        self.workspace.activeWindow().copy()
        self.setActionsEnabled()

    def paste(self):
        self.workspace.activeWindow().paste()
        self.setActionsEnabled()

    def delete(self):
        self.workspace.activeWindow().delete()
        self.setActionsEnabled()

    def selectAll(self):
        self.workspace.activeWindow().selectAll()
        self.setActionsEnabled()

    def options(self):
        feOptions = FeOptions()
        feOptions.exec_()

        
    def about(self):
        feAbout = FeAbout()
        feAbout.exec_()


    def onClipboardDataChanged(self):
        self.setActionsEnabled()


    def setActionsEnabled(self, widget=None):
        widget = self.workspace.activeWindow()
        if widget is None:
            self.setCanCopy(False)
            self.setCanSave(False)
            self.setActiveWindowExists(False)
            self.ui.actionPaste.setEnabled(False)

            self.statusLabel.setText("")
        else:
            self.setCanCopy(widget.selectionExists())
            self.setCanSave(widget.modified())
            self.setActiveWindowExists(True)
            self.ui.actionPaste.setEnabled(len(QtGui.QApplication.clipboard().text()) > 0)

            self.statusLabel.setText(widget.windowTitle())


    def setCanCopy(self, value):
        self.ui.actionCut.setEnabled(value)
        self.ui.actionCopy.setEnabled(value)
        self.ui.actionDelete.setEnabled(value)

    def setCanSave(self, value):
        self.ui.actionSave.setEnabled(value)

    def setActiveWindowExists(self, value):
        self.ui.actionSelectAll.setEnabled(value)
        self.ui.actionPaste.setEnabled((value and QtGui.QApplication.clipboard().text()) == True)
        self.ui.actionSaveAs.setEnabled(value)
        self.ui.actionExportPdf.setEnabled(value)
        self.ui.actionClose.setEnabled(value)
        self.ui.actionCloseAll.setEnabled(value)
            

    


    def exportPdf(self):
        filename = self.getSaveFileName(MainWindow.extPdf, MainWindow.extPdfUser)
        if filename is None:
            return
        
        try:
            printer = QtGui.QPrinter()
            printer.setOutputFormat(QtGui.QPrinter.PdfFormat)
            printer.setOutputFileName(filename)
            self.workspace.activeWindow().printDocument(printer)
        except (Exception), e:
            QtGui.QMessageBox.critial(self, u"Ошибка", u"Не могу экспортировать в Pdf. {0}".format(unicode(e)))
        else:
            QtGui.QMessageBox.information(self, u"Сообщение", u"Данные успешно экспортированы в Pdf.")


    extMcf = u"mcf"
    extMcfUser = u"Коллекции фильмов (*.{0})".format(extMcf)

    extPdf = u"pdf"
    extPdfUser = u"*.{0}".format(extPdf)


    
if __name__ == "__main__":
    app = QtGui.QApplication([])

    Options.load()
    dialog = MainWindow()
    dialog.show()
    app.exec_()
    
    
